package com.weilai.service.serviceImpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.weilai.controller.exceptionHandler.BusinessException;
import com.weilai.controller.exceptionHandler.Code;
import com.weilai.dao.VideosDao;
import com.weilai.domain.*;
import com.weilai.service.VideosService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class VideosServiceImpl implements VideosService {

    @Autowired
    private VideosDao videosDao;

    @Override
    public Videos selectById(int id) {
        return videosDao.selectById(id);
    }

    @Override
    public List<Videos> selectByUserId(int id) {
        return videosDao.selectByUserId(id);
    }

    @Override
    @Transactional
    public void addVideoDescription(Videos videos) {
        // 验证标签（描述添加时需要标签）
        validateTagExists(videos.getTagId());
        setCommonFields(videos);
        videosDao.addDescription(videos);
    }

    @Override
    @Transactional
    public void addVideoFile(Videos videos) {
        // 上传文件时不需要标签，不验证标签ID
        setCommonFields(videos);
        videosDao.addFile(videos);
    }

    private void setCommonFields(Videos videos) {
        videos.setUploadTime(LocalDateTime.now());
    }

    private void validateTagExists(Integer tagId) {
        if (tagId == null || tagId <= 0) {
            throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "无效的标签ID");
        }
        Tag tag = videosDao.getById(tagId);
        if (tag == null) {
            throw new BusinessException(Code.PROJECT_VALIDATE_ERROR, "标签ID不存在：" + tagId);
        }
    }

    @Override
    public void deleteById(int id) {
        videosDao.deleteById(id);
    }

    @Override
    public void update(Videos video) {
        videosDao.update(video);
    }

    @Override
    public PageInfo<Videos> selectAllVideos(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Videos> videos = videosDao.selectAllVideos();
        return new PageInfo<>(videos);
    }

    @Override
    public List<Videos> selectAllUsersVideos(int userId) {
        return videosDao.selectAllUsersVideos(userId);
    }

    @Override
    public List<Videos> selectMyAllVideos(int userId) {
        return videosDao.selectMyAllVideos(userId);
    }

    @Override
    public List<Videos> selectByTitle(String title) {
        List<Videos> videos = videosDao.selectByTitle(title);
        if(videos==null||videos.isEmpty())
            return new ArrayList<>();
        else
            return videos;
    }

    @Override
    public List<Videos> selectByDate(String date1, String date2) {
        List<Videos> videos = videosDao.selectByDate(date1, date2);
        if(videos==null||videos.isEmpty())
            return new ArrayList<>();
        else
            return videos;
    }

    //进入视频前查询用户是否点赞
    @Override
    public boolean isLikedByUser(int userId, int videoId) {
        return videosDao.countUserLiked(userId, videoId) > 0;
    }

    @Override
    public  int isLiked(int videoId,int userId){
        int count = videosDao.countUserLiked(userId, videoId);
        if(count==0)
            return 0;
        return 1;
    }

    @Override
    public Map<String, Object> like(int userId, int videoId) {
        Map<String, Object> result = new HashMap<>();
        int count = videosDao.countUserLiked(userId, videoId);
        if (count == 0) {
            videosDao.incrementLikeCount(videoId);
            videosDao.insertLikeRecord(userId, videoId);
            result.put("message", "点赞成功");
        } else {
            result.put("message", "您已点赞过，不能重复点赞");
        }
        // 获取更新后的点赞数
        int likeCount = videosDao.likeCount(videoId);
        result.put("likeCount", likeCount);
        return result;
    }
    @Override
    public Map<String, Object> cancelLike(int userId, int videoId) {
        Map<String, Object> result = new HashMap<>();
        Likes likeRecord = videosDao.selectLikeRecord(userId, videoId);
        if (likeRecord != null) {
            int likeId = likeRecord.getId();
            videosDao.cancelLikeRecord(likeId,videoId);
            videosDao.decrementLikeCount(videoId);
            videosDao.delete(userId,videoId);
            result.put("message", "取消点赞成功");
        } else {
            result.put("message", "您尚未点赞，无法取消");
        }
        // 获取更新后的点赞数
        int likeCount = videosDao.likeCount(videoId);
        result.put("likeCount", likeCount);
        return result;
    }

    @Override
    public String comment(Comments comments) {
        videosDao.incrementCommentCount(comments.getVideoId());
        //获取当前时间
        comments.setCreatedAt(LocalDateTime.now());
        videosDao.insertCommentRecord(comments);
        return "评论成功";
    }

    @Override
    public List<Comments> getCommentsByVideoId(int videoId) {
        return videosDao.getCommentsByVideoId(videoId);
    }

    @Override
    public void view(int videoId) {
        videosDao.incrementViewCount(videoId);
    }

    @Override
    public void share(int videoId) {
        videosDao.incrementShareCount(videoId);
    }

    @Override
    public String deleteCommentByUser(int commentId, int userId) {
        int result = videosDao.deleteCommentByUser(commentId, userId);
        if (result > 0) {
            int videoId = videosDao.getVideoIdByCommentId(commentId);
            videosDao.decrementCommentCount(videoId);
            return "评论删除成功";
        } else {
            return "删除失败，您可能没有权限或评论不存在";
        }
    }

    @Override
    public String deleteCommentByAuthor(int commentId, int userId) {
        int result = videosDao.deleteCommentByAuthor(commentId, userId);
        if (result > 0) {
            int videoId = videosDao.getVideoIdByCommentId(commentId);
            videosDao.decrementCommentCount(videoId);
            return "评论删除成功";
        } else {
            return "删除失败，您可能没有权限或评论不存在";
        }
   }
    @Override
    public Comments getCommentById(int commentId) {
        // 调用DAO层获取评论
        Comments comment = videosDao.getCommentById(commentId);
        if (comment == null) {
            throw new BusinessException(Code.PROJECT_DATA_NOT_FOUND,"评论不存在");
        }
        return comment;

    }

    @Override
    public List<Videos> selectByKeywords(String keywords) {
        List<Videos> videos = videosDao.selectByKeywords(keywords);
        if(videos==null||videos.isEmpty()){
            return new ArrayList<>();
        }
        return videos;
    }

    // 按 userid 删除视频
    @Override
    public void deleteUserById(int userId){
        try {
            videosDao.deleteUserById(userId);
        } catch (Exception e) {
            throw new BusinessException(Code.SYSTEM_DB_ERROR, "按id删除用户信息时数据库出错");
        }
    }

    //按userId查询视频数据
    @Override
    public List<Videos> selectData(int userId){
        try{
            return videosDao.selectData(userId);
        } catch (Exception e) {
            throw new BusinessException(Code.SYSTEM_DB_ERROR, "按id查询视频数据时数据库出错");
        }
    }
//    @Override
//    public int selectTagById(String name){
//        return videosDao.selectTagById(name);
//    }
    @Override
    public Tag getTagByTagName(String tagName) {
        return videosDao.findByTagName(tagName);
    }
}



